//
//  InfinityScrollView.m
//  ScrollView无限轮播
//
//  Created by LeungChaos on 16/4/6.
//  Copyright © 2016年 liang. All rights reserved.
//

#import "InfinityScrollView.h"
#import "UIView+ResetFrame.h"

#import "UIImageView+BOCNetworkImage.h"

#import "UIImageView+WebCache.h"

#import "BOCNetworkImage.h"

#import "BOCActivityView.h"

@interface InfinityScrollView ()<UIScrollViewDelegate>

@property (nonatomic, weak) UIImageView *leftView;
@property (nonatomic, weak) UIImageView *centerView;
@property (nonatomic, weak) UIImageView *rightView;
@property (nonatomic, assign) NSUInteger currentIndex;

@property (nonatomic, assign ,getter=isNetwork) BOOL network;
@property (nonatomic, copy) IndexDidChangeBlock indexBlock;
@end

@implementation InfinityScrollView

- (UIImageView *)leftView
{
    if (_leftView == nil) {
        _leftView = [self creatImageView];
    }
    return _leftView;
}

- (UIImageView *)centerView
{
    if ( _centerView == nil) {
        _centerView = [self creatImageView];
    }
    return _centerView;
}

- (UIImageView *)rightView
{
    if (_rightView == nil) {
        _rightView = [self creatImageView];
    }
    return _rightView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.delegate = self;
        self.pagingEnabled = YES;
        self.showsHorizontalScrollIndicator = NO;
        self.showsVerticalScrollIndicator = NO;
        self.bounces = NO;
    }
    return self;
}

- (instancetype)initWithImageNames:(NSArray <NSString *>*)imageNames isNetwork:(BOOL ) isNetwork indexDidChangeBlock:(IndexDidChangeBlock)indexDidChangeBlock
{
    if (self = [super init]) {
        self.network = isNetwork;
        self.indexBlock = indexDidChangeBlock;
        self.imageNamesArray = imageNames;
    }
    return self;
}

+ (instancetype)infinityScrollViewWithImageNames:(NSArray <NSString *>*)imageNames isNetwork:(BOOL ) isNetwork
{
    return [[self alloc]initWithImageNames:imageNames isNetwork:isNetwork indexDidChangeBlock:nil];
}

+ (instancetype)infinityScrollViewWithImageNames:(NSArray <NSString *>*)imageNames isNetwork:(BOOL ) isNetwork indexDidChangeBlock:(IndexDidChangeBlock)indexDidChangeBlock
{
    return [[self alloc]initWithImageNames:imageNames isNetwork:isNetwork indexDidChangeBlock:indexDidChangeBlock];
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    CGFloat w = self.width;
    CGFloat h = self.height;
    
    self.contentSize = CGSizeMake(w * 3, h);
    self.contentOffset = CGPointMake(w, 0);
    
    CGRect tempFrame = self.frame;
    
    [self.leftView setFrame:tempFrame];
    
    tempFrame.origin.x += w;
    [self.centerView setFrame:tempFrame];
    
    tempFrame.origin.x += w;
    [self.rightView setFrame:tempFrame];
}

- (void)setImageNamesArray:(NSArray<NSString *> *)imageNamesArray
{
    _imageNamesArray = imageNamesArray;
    [self configImageViews];
    [self imageIndexDidChange];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.imageNamesArray.count) {
        
        if (scrollView.contentOffset.x > scrollView.width) {
            
            self.currentIndex = [self currentIndexPlus];
            [self imageIndexDidChange];
            scrollView.contentOffset = CGPointMake(scrollView.width, 0);
            if (self.isNetwork) {
                [self changeImageOnline];
            } else {
                [self changeImage];
            }
            
        } else if (scrollView.contentOffset.x < scrollView.width) {
            scrollView.contentOffset = CGPointMake(scrollView.width, 0);
            
            self.currentIndex = [self currentIndexSub];
            [self imageIndexDidChange];
            if (self.isNetwork) {
                [self changeImageOnline];
            } else {
                [self changeImage];
            }
        
        }
    }
}

- (NSUInteger)currentIndexPlus
{
    NSUInteger index = self.currentIndex;
    if (index == self.imageNamesArray.count-1) {
        index = 0;
    } else {
        index ++;
    }
    return index;
}

- (NSUInteger)currentIndexSub
{
    NSUInteger index = self.currentIndex;
    if (index == 0) {
        index = self.imageNamesArray.count-1;
    } else {
        index --;
    }
    return index;
}

#pragma mark - 私有的方法
- (void)configImageViews
{
    if (self.imageNamesArray.count) {
        if (self.network == YES) {
            [self changeImageOnline];
        } else {
            [self changeImage];
        }
    }
}

- (UIImage *)imageWithfileName:(NSString *)imageName
{
    return [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:imageName ofType:nil]];
}

- (void)changeImage
{
    [self.centerView setImage:[self imageWithfileName:self.imageNamesArray[self.currentIndex]]];
    [self.leftView setImage:[self imageWithfileName:self.imageNamesArray[self.currentIndexSub]]];
    [self.rightView setImage:[self imageWithfileName:self.imageNamesArray[self.currentIndexPlus]]];
}

- (void)changeImageOnline
{
    __weak typeof(self) weakSelf = self;
    [BOCActivityView showInView:weakSelf.centerView];
//    
    [weakSelf.centerView setNetworkImageWithURL:[NSURL URLWithString:weakSelf.imageNamesArray[weakSelf.currentIndex]] progress:^(NSProgress * _Nonnull progress) {
        
        NSLog(@"%f", 1.0 * progress.completedUnitCount / progress.totalUnitCount);
        
    } completion:^(UIImage *image, NSURLResponse *response, NSError *error) {
        
        [BOCActivityView stopAllAnimatingAndRemoveFromView:weakSelf.centerView];
    }];
    
//    [weakSelf.centerView sd_setImageWithURL:[NSURL URLWithString:weakSelf.imageNamesArray[weakSelf.currentIndex]] placeholderImage:nil options:kNilOptions progress:^(NSInteger receivedSize, NSInteger expectedSize) {
//        NSLog(@"%f",1.0 * receivedSize / expectedSize);
//    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//        [BOCActivityView stopAllAnimatingAndRemoveFromView:weakSelf.centerView];
//
//    }];
    
    
    [BOCActivityView showInView:weakSelf.leftView];
    [weakSelf.leftView setNetworkImageWithURL:[NSURL URLWithString:weakSelf.imageNamesArray[weakSelf.currentIndexSub]] progress:^(NSProgress * _Nonnull progress) {
        
        NSLog(@"%f", 1.0 * progress.completedUnitCount / progress.totalUnitCount);
        
    } completion:^(UIImage *image, NSURLResponse *response, NSError *error) {
        [BOCActivityView stopAllAnimatingAndRemoveFromView:weakSelf.leftView];
    }];
    
//    [weakSelf.leftView sd_setImageWithURL:[NSURL URLWithString:weakSelf.imageNamesArray[weakSelf.currentIndexSub]] placeholderImage:nil options:kNilOptions progress:^(NSInteger receivedSize, NSInteger expectedSize) {
//        NSLog(@"%f",1.0 * receivedSize / expectedSize);
//    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//        [BOCActivityView stopAllAnimatingAndRemoveFromView:weakSelf.leftView];
//        
//    }];

    
    [BOCActivityView showInView:weakSelf.rightView];
    
    [weakSelf.rightView setNetworkImageWithURL:[NSURL URLWithString:weakSelf.imageNamesArray[weakSelf.currentIndexPlus]] progress:^(NSProgress * _Nonnull progress) {
        
        NSLog(@"%f", 1.0 * progress.completedUnitCount / progress.totalUnitCount);
        
    } completion:^(UIImage *image, NSURLResponse *response, NSError *error) {
        [BOCActivityView stopAllAnimatingAndRemoveFromView:weakSelf.rightView];
    }];
    
//    [weakSelf.rightView sd_setImageWithURL:[NSURL URLWithString:weakSelf.imageNamesArray[weakSelf.currentIndexPlus]] placeholderImage:nil options:kNilOptions progress:^(NSInteger receivedSize, NSInteger expectedSize) {
//        NSLog(@"%f",1.0 * receivedSize / expectedSize);
//    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//        [BOCActivityView stopAllAnimatingAndRemoveFromView:weakSelf.rightView];
//        
//    }];

    
}

- (void)imageIndexDidChange
{
    if (self.indexBlock) {
        NSInteger index = self.currentIndex;
        self.indexBlock(index);
    }
    if ([self.infDelegate respondsToSelector:@selector(currentImageIndex:)]) {
        [self.infDelegate currentImageIndex:self.currentIndex];
    }
}

- (UIImageView *)creatImageView
{
    UIImageView *imgView = [[UIImageView alloc]init];
    [self addSubview:imgView];
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    return imgView;
}

- (void)dealloc
{
    
}


@end
